<template>
  <div id="eqMaintainOrderDiv">
    <Breadcrumb content="巡检计划管理" />
    <div class="bodyContent">
      <Splitpanes horizontal class="horizontalLine">
        <Pane size="60">
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-input style="width: 180px" v-model="searchForm.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findPatrolPlanList" @keyup="keyupEnter" @search-click="findPatrolPlanList()"></vxe-input>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="查询" :loading="tloading" @click="findPatrolPlanList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新增巡检计划" @click="addMaintainDialog()"></vxe-button>
              <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="deleteBatchPatrolTask"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="tableBody">
            <div style="height: calc(100% - 32px)">
              <vxe-table ref="patrolPlanTableRef" class="mytable-scrollbar supplierTableClazz" border="inner" align="center" height="auto" :data="patrolPlanList" :loading="tloading" @current-change="patrolTaskRowClick" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
                <vxe-column type="seq" width="30" title=""></vxe-column>
                <vxe-column type="checkbox" width="20"></vxe-column>
                <vxe-column field="code" title="计划编号"> </vxe-column>
                <vxe-column field="name" title="计划名称">
                  <template #default="{ row }">
                    <el-link
                        type="primary"
                        :underline="false"
                        @click="editPlanShow(row.id)"
                    >{{row.name}}
                    </el-link>
                  </template>
                </vxe-column>
                <vxe-column field="name" title="执行人"> </vxe-column>
                <vxe-column field="beginTime" title="开始时间"> </vxe-column>
                <vxe-column field="endTime" title="结束时间"> </vxe-column>
                <vxe-column field="nextTime" title="下次执行时间"> </vxe-column>
                <vxe-column field="status" title="状态" width="80">
                  <template #default="{ row }">
                   <el-tag :type="getTagType(row)">
                     <span>{{ formatCommon(planStatusList, row.status) }}</span>
                    </el-tag>
                  </template>
                </vxe-column>
                <vxe-column title="操作" fixed="right" width="240" align="center">
                  <template #default="{ row }">
                    <vxe-button type="text" v-if="row.status==5||row.status==10" status="primary" icon="vxe-icon-picture" content="暂停" @click="handleStopStart(row.id,'4')"></vxe-button>
                    <vxe-button type="text" v-if="row.status==4" status="primary" icon="vxe-icon-caret-right" content="开启" @click="handleStopStart(row.id,'10')"></vxe-button>
                    <vxe-button type="text" v-if="row.status>0" status="primary" icon="vxe-icon-send" content="执行" @click="handleExecute(row.id)"></vxe-button>
                  </template>
                </vxe-column>
              </vxe-table>
            </div>
            <vxe-pager align="left" :current-page.sync="page.currentPage" :page-size.sync="page.pageSize" :total="page.totalResult" :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']" @page-change="handleSizeChange($event)"></vxe-pager>
          </div>
        </Pane>
        <Pane size="40">
          <el-tabs type="border-card" v-model="activeName" @tab-click="tabHandleClick">
            <el-tab-pane label="巡检任务" name="first">
              <div class="tableBody">
                <vxe-table ref="patrolTaskTableRef" class="mytable-scrollbar supplierTableClazz" border="inner" align="center" height="auto" :data="patrolTaskList" :loading="tloading"  :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
                  <vxe-column type="seq" width="30" title="序号"></vxe-column>
                  <vxe-column type="checkbox" width="20"></vxe-column>
                  <vxe-column field="code" title="编号"> </vxe-column>
                  <vxe-column field="name" title="名称"> </vxe-column>
                  <vxe-column field="status" title="巡检状态">
                    <template #default="{ row }">
                      <el-tag :type="getTagType(row)">
                        <span>{{ getTaskStatusDesc( row.status) }}</span>
                      </el-tag>
                    </template>
                  </vxe-column>
                  <vxe-column field="beginTime" title="开始时间"> </vxe-column>
                  <vxe-column field="endTime" title="结束时间"> </vxe-column>
                  <vxe-column title="操作" fixed="right" width="180" align="center">
                    <template #default="{ row }">
                      <vxe-button type="text" status="primary" icon="vxe-icon-edit" content="编辑" @click="editTaskShow({ row })"></vxe-button>
                      <vxe-button type="text" status="danger" icon="vxe-icon-delete"  content="删除" @click="deleTask({ row })"></vxe-button>
                    </template>
                  </vxe-column>
                </vxe-table>
              </div>
            </el-tab-pane>
          </el-tabs>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
let { proxy }: any = getCurrentInstance();
import { AppStore } from '@/stores/store';
import { IsEmpty } from '@/utils/common'; //'../../../stores/store';

let store = AppStore();

// 全局变量定义区 ==========
let searchForm = {
  searchValue: ''
};
let tloading = ref(false); //加载状态
let ploading = ref(false); //加载状态

let patrolPlanList: any = reactive([]);
let patrolTaskList: any = reactive([]);
let planStatusList: any = reactive([]); //选择字典
let inspectionStatusList: any = reactive([]); //选择字典
let eqPatrolPlan: any = ref({});
let activeName = ref('first');

// 条数/页
const PageSizeList = [10, 50, 100, 200, 500];
// 分页
let page = reactive({
  currentPage: 1,
  pageSize: PageSizeList[1],
  totalResult: 0
});

// 方法定义区 =============
// 页面加载时更新列表(左侧)
onMounted(() => {
  findPatrolPlanList(); // 获取质控规则表格数据
  getDictItemsList();
});

//批量获取字典
async function getDictItemsList() {
  let dictTreeTypeCodes: any = ['planStatus','inspectionStatus'];
  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  const planStatues = dictTreeTypeItems.data.find((item: any) => item.code === 'planStatus');
  planStatusList.push(...planStatues.detailDataList);
  const inspectionStatus = dictTreeTypeItems.data.find((item) => item.code === 'inspectionStatus');
  inspectionStatusList.push(...inspectionStatus.detailDataList);
}
// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findPatrolPlanList();
  }
}

//点击每页数量(分页查询)
function handleSizeChange({ type, currentPage, pageSize }) {
  if (type === 'size') {
    page.currentPage = 1;
  } else {
    page.currentPage = currentPage;
  }
  page.pageSize = pageSize;
  findPatrolPlanList();
}
function findPatrolPlanList() {
  tloading.value = true;
  patrolPlanList.length = 0; //放入数据前清空数据
  const url = '/api/eq/patrolPlan/findPatrolPlanPageList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        seachValue: searchForm.searchValue,
        pageIndex: page.currentPage,
        pageSize: page.pageSize
      }
    })
    .then((res: any) => {
      patrolPlanList.push(...res.data.records);
      page.totalResult = res.data.total;
      const kn = patrolPlanList.find((k: any) => k.id == eqPatrolPlan.value.id);
      if (IsEmpty(kn)) {
        patrolTaskRowClick({ row: patrolPlanList[0] }); //默认选中第一条数据
      } else {
        patrolTaskRowClick({ row: kn }); //默认选中第一条数据
      }
      tloading.value = false;
    })
    .catch((err: any) => {
      tloading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}

function patrolTaskRowClick({ row }: any) {
  if (IsEmpty(row)) {
    eqPatrolPlan.value = {};
    patrolTaskList.length = 0; //放入数据前清空数据
  } else {
    (proxy.$refs.patrolPlanTableRef as any).setCurrentRow(row);
    eqPatrolPlan.value = row;
    if (activeName.value == 'first') {
      getPatrolTaskList();
    }
  }
}

function tabHandleClick(tab) {
  if (tab.index == 0) {
    getPatrolTaskList();
  }
}

function getPatrolTaskList() {
  ploading.value = true;
  patrolTaskList.length = 0; //放入数据前清空数据
  const url = '/api/eq/patrolTask/findPatrolTaskByPlanId';
  proxy.$http
    //注意此处的数据条数
    .get(url, {params: {planId: eqPatrolPlan.value.id}})
    .then((res: any) => {
      if (res.status.code === 1) {
        patrolTaskList.push(...res.data);
      }
      ploading.value = false;
    })
    .catch((err: any) => {
      ploading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}

function deleteBatchPatrolTask() {
  const sltMaintainOrders = (proxy.$refs.patrolPlanTableRef as any).getCheckboxRecords();
  if (!(sltMaintainOrders.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy.$XModal.confirm('您确定要删除吗？').then((type) => {
      if (type === 'confirm') {
        //后台删除数据
        const delMaintainOrderList = sltMaintainOrders.filter((p: any) => !IsEmpty(p.id));
        if (delMaintainOrderList.length > 0) {
          const url = '/api/eq/patrolPlan/deletePatrolPlan';
          proxy.$http
              .post(url, delMaintainOrderList)
              .then((res: any) => {
                findPatrolPlanList(); // 获取检验仪器表格数据
                VxeMessage('删除成功!', VxeNotifyType.success);
              })
              .catch((err: any) => {
                VxeMessage(err, VxeNotifyType.error);
              });
        }
      }

      })
  }
}
function editTaskShow({ row }) {
  const data = {
    id: row.id,
    url: '/eqPatrolPlan'
  };
  proxy.$router.push({ path: '/patrolTaskEdit', query: data });
}

function deleTask({row}) {
  const delMaintainOrderList = [];
  delMaintainOrderList.push(row)
  proxy.$XModal.confirm('您确定要删除吗？').then((type) => {
    if (type === 'confirm') {
      //后台删除数据
      const url = '/api/eq/patrolTask/deletePatrolTask';
      proxy.$http
          .post(url, delMaintainOrderList)
          .then((res: any) => {
            getPatrolTaskList();
            VxeMessage('删除成功!', VxeNotifyType.success);
          })
          .catch((err: any) => {
            VxeMessage(err, VxeNotifyType.error);
          });
    }
  })
}
//编辑
function editPlanShow(id:any) {
  const data = {
    id: id,
    url: '/eqPatrolPlan',
  };
  proxy.$router.push({ path: '/patrolPlanEdit', query: data });
  // 路由传值并携带参数id
}
function addMaintainDialog() {
  const data = {
    url: '/eqPatrolPlan'
  };
  proxy.$router.push({ path: '/patrolPlanEdit', query: data });
}

function getTagType(row: any) {
  const status = row.status;
  if (status == '0') {
    return 'warning';
  } else if (status == '5') {
    return 'success';
  } else if (status == '10') {
    return 'success';
  } else if (status == '99') {
    return 'info';
  }
}
function formatCommon(arr: any, value: any) {
  for (const item of arr) {
    if (item.code == value) {
      return item.name;
    }
  }
}
function getTaskStatusDesc(scope: any) {
  for (const item of inspectionStatusList) {
    if (scope == item.code) {
      return item.name;
    }
  }
}


//启动停止
function handleStopStart(id, status) {
  let msg = '';
  if (status === '4') {
    msg = '确定暂停？';
  } else if (status === '10') {
    msg = '确定开启？';
  }
  proxy.$confirm(msg, '提示', {
    cancelButtonClass: 'cancelbutton',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const url = '/api/eq/patrolPlan/patrolPlanStopStart';
    const data = {
      id:id,
      status:status
    };
    proxy.$http
        .post(url, data)
        .then((res: any) => {
          if (res.status.code !== 1) {
            proxy.$alert(res.status.msg, '提示');
          } else {
            findPatrolPlanList();
          }
        }).catch((err) => {
      VxeMessage(err, VxeNotifyType.error);

    });
  }).catch((err) => {
    console.log(err);
  });
}
//执行任务
function handleExecute(id) {
  proxy.$confirm('确定执行此方案?', '提示', {
    cancelButtonClass: 'cancelbutton',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const url = '/api/eq/patrolPlan/handleExecutePlan';
    proxy.$http.get(url, {params: {id: id}})
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('执行成功', VxeNotifyType.success);
            getPatrolTaskList();
          } else {
            proxy.$alert(res.status.msg, '提示');
          }
        }).catch((err) => {
      console.log(err);
    });
  }).catch((err) => {
    console.log(err);
  });
}

</script>

<style lang="scss" scoped>
#eqMaintainOrderDiv {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .splitpanes {
      background-color: $base-white;
      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
    }
    .horizontalLine {
      :deep(.splitpanes__splitter) {
        background-color: $base-white;
      }
    }

    // 中间table表格
    .tableBody {
      height: calc(100% - 40px);
    }
    // 质控靶值设定弹框表格
    .tableTargetBody {
      height: 600px;
      .tableTargetBodyRight {
        height: calc(100% - 2px);
        border: 1px solid #e8eaec;

        .closeBtn {
          margin-left: 720px;
        }
      }
    }

    // 右侧保存按钮
    .saveBtn {
      float: right;
      margin: 5px 10px;
    }
    .el-form {
      padding-right: 15px;
      .el-form-item--large {
        margin-bottom: 10px;
      }
      .el-button {
        padding: 5px 2px !important;
      }
      :deep(.el-input__inner) {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }

    // 弹框
    .el-dialog {
      font-weight: 700;
      max-height: 1000px;
      padding: 10px;
    }
    // 最右侧质控项目设定表格
    .tableBox {
      height: calc(100% - 40px);
    }
  }

  :deep(.el-tabs) {
    height: 100%;
    .el-tabs__content {
      height: calc(100% - 70px);
      .el-tab-pane {
        height: 100%;
      }
    }
  }
}
</style>
